package com.xoa.service.easyReport.impl;

import com.xoa.dao.easyReport.RepFieldMapper;
import com.xoa.dao.easyReport.RepTableMapper;
import com.xoa.model.easyReport.RepField;
import com.xoa.model.easyReport.RepTable;
import com.xoa.service.easyReport.RepFieldService;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;

@Service
public class RepFieldServiceImpl implements RepFieldService {

    @Resource
    RepTableMapper repTableMapper;
    @Resource
    RepFieldMapper repFieldMapper;

    @Override
    public ToJson<RepField> inserRepField(RepField repField) {
        ToJson<RepField> toJson = new ToJson<>(1, "err");
        int i = repFieldMapper.insertSelective(repField);
        if (i > 0) {
            toJson.setFlag(0);
            toJson.setMsg("true");
        }
        return toJson;
    }

    @Override
    public ToJson<RepField> importField(MultipartFile file, Integer repTableId) {
        ToJson<RepField> toJson = new ToJson<>(1, "err");
        if (file.isEmpty()) {
            toJson.setMsg("请上传文件！");
            return toJson;
        }
        if (repTableId != null) {
            try (InputStream in = file.getInputStream();) {
                RepTable repTable = repTableMapper.selectByPrimaryKey(repTableId);
                if (repTable != null) {
                    String fileName = file.getOriginalFilename();
                    Workbook wb;
                    if (fileName.matches("^.+\\.(?i)(xls)$")) {
                        wb = new HSSFWorkbook(in);
                    } else if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                        wb = new XSSFWorkbook(in);
                    } else {
                        toJson.setMsg("必须是 .xls 或者 .xlsx 文件");
                        return toJson;
                    }
                    Sheet Sheet = wb.getSheetAt(0);
                    if (Sheet != null) {
                        List<RepField> repTables = new ArrayList();
                        int lastRowNum = Sheet.getLastRowNum();
                        Map<String, String> rowMsg = new HashMap();
                        for (int rowNum = 1; rowNum <= lastRowNum; rowNum++) {
                            boolean bol = true;
                            Row row = Sheet.getRow(rowNum);
                            if (row == null)
                                continue;
                            RepField repField = new RepField();
                            repField.setRepTableId(repTable.getRepTableId());
                            int physicalNumberOfCells = row.getLastCellNum();
                            for (int i = 0; i < physicalNumberOfCells; i++) {
                                Cell cell = row.getCell(i);
                                if (cell == null)
                                    continue;
                                cell.setCellType(CellType.STRING); //统一单元格类型
                                String stringCellValue = cell.getStringCellValue();
                                switch (i) {
                                    case 0://排序号
                                        if (!StringUtils.checkNull(stringCellValue)) {
                                            if (stringCellValue.matches("\\d+")) {
                                                repField.setFiledNo(Integer.valueOf(stringCellValue));
                                            } else {
                                                rowMsg.put("row:" + (rowNum + 1) + "column:" + (i + 1), "FILED_NO:" + "字段排序号必须为数字");
                                            }
                                        }
                                        break;
                                    case 1://字段名称
                                        if (!StringUtils.checkNull(stringCellValue)) {
                                            repField.setFieldName(stringCellValue);
                                        } else {
                                            bol = false;
                                            rowMsg.put("row:" + (rowNum + 1) + "column:" + (i + 1), "FIELD_NAME:" + "字段名称不能为空");
                                        }
                                        break;
                                    case 2://分组
                                        if (!StringUtils.checkNull(stringCellValue)) {
                                            repField.setFieldGroup(stringCellValue);
                                        }
                                        break;
                                    case 3://类型
                                        //1单行文本 2单行数字  3多行文本  4日期 5单选 6 多选
                                        if (!StringUtils.checkNull(stringCellValue)) {
                                            switch (stringCellValue) {
                                                case "单行文本":
                                                    stringCellValue = "1";
                                                    break;
                                                case "单行数字":
                                                    stringCellValue = "2";
                                                    break;
                                                case "多行文本":
                                                    stringCellValue = "3";
                                                    break;
                                                case "日期":
                                                    stringCellValue = "4";
                                                    break;
                                                case "单选":
                                                    stringCellValue = "5";
                                                    break;
                                                case "多选":
                                                    stringCellValue = "6";
                                                    break;
                                                default:
                                                    stringCellValue = "1";
                                                    break;
                                            }
                                            repField.setFieldType(stringCellValue);
                                        } else {
                                            bol = false;
                                            rowMsg.put("row:" + (rowNum + 1) + "column:" + (i + 1), "FIELD_TYPE:" + "字段类型不能为空");
                                        }
                                        break;
                                    case 4://选项内容
                                        repField.setFieldContent(stringCellValue);
                                        if (("5".equals(repField.getFieldType()) || "6".equals(repField.getFieldType()))
                                                && (StringUtils.checkNull(stringCellValue) || !stringCellValue.contains("/"))) {
                                            bol = false;
                                            rowMsg.put("row:" + (rowNum + 1) + "column:" + (i + 1), "FIELD_CONTENT:" + "选项内容格式错误");
                                        }
                                        break;
                                    case 5://字段说明
                                        if (!StringUtils.checkNull(stringCellValue)) {
                                            repField.setFieldDesc(stringCellValue);
                                        }
                                        break;
                                    case 6://字段长度
                                        if (!StringUtils.checkNull(stringCellValue)) {
                                            if (stringCellValue.matches("\\d+")) {
                                                repField.setFieldSize(Integer.valueOf(stringCellValue));
                                            } else {
                                                rowMsg.put("row:" + (rowNum + 1) + "column:" + (i + 1), "FIELD_SIZE:" + "字段长度必须为数字");
                                            }
                                        }
                                        break;
                                    case 7://字段是否必填(0-非必填，1-必填字段)
                                        if (!StringUtils.checkNull(stringCellValue)) {
                                            switch (stringCellValue) {
                                                case "非必填":
                                                    stringCellValue = "0";
                                                    break;
                                                case "必填":
                                                    stringCellValue = "1";
                                                    break;
                                                default:
                                                    stringCellValue = "0";
                                                    break;
                                            }
                                            repField.setIsmust(stringCellValue);
                                        }else{
                                            repField.setIsmust("0");
                                        }
                                        break;
                                    case 8://字段是否分组统计
                                        if (!StringUtils.checkNull(stringCellValue)) {
                                            switch (stringCellValue) {
                                                case "否":
                                                    stringCellValue = "0";
                                                    break;
                                                case "是":
                                                    stringCellValue = "1";
                                                    break;
                                                default:
                                                    stringCellValue = "0";
                                                    break;
                                            }
                                            repField.setIsgroup(stringCellValue);
                                        }else{
                                            repField.setIsgroup("0");
                                        }
                                        break;
                                    case 9://字段是否只读
                                        if (!StringUtils.checkNull(stringCellValue)) {
                                            switch (stringCellValue) {
                                                case "否":
                                                    stringCellValue = "0";
                                                    break;
                                                case "是":
                                                    stringCellValue = "1";
                                                    break;
                                                default:
                                                    stringCellValue = "0";
                                                    break;
                                            }
                                            repField.setReadonly(stringCellValue);
                                        }else{
                                            repField.setReadonly("0");
                                        }
                                        break;
                                }
                            }
                            if (bol) {
                                repTables.add(repField);
                            } else {
                                rowMsg.put("row:" + (rowNum + 1), "添加失败");
                            }
                        }
                        toJson.setObject(rowMsg);
                        if (repTables.size() > 0) {
                            int i = repFieldMapper.insertAll(repTables);
                            toJson.setObj1(i);
                            toJson.setFlag(0);
                            toJson.setMsg("true");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                toJson.setMsg(e.getMessage());
            }
        } else {
            toJson.setMsg("报表不存在");
        }
        return toJson;
    }

    @Override
    public ToJson<RepField> updateRepField(RepField repField) {
        ToJson<RepField> toJson = new ToJson<>(1, "err");
        int i = repFieldMapper.updateByPrimaryKeySelective(repField);
        if (i > 0) {
            toJson.setFlag(0);
            toJson.setMsg("true");
        }
        return toJson;
    }

    @Override
    public ToJson<RepField> deleteRepField(Integer fieldId) {
        ToJson<RepField> toJson = new ToJson<>(1, "err");
        int i = repFieldMapper.deleteByPrimaryKey(fieldId);
        if (i > 0) {
            toJson.setFlag(0);
            toJson.setMsg("true");
        }
        return toJson;
    }

    @Override
    public ToJson<RepField> getFieldByFieldId(Integer fieldId) {
        ToJson<RepField> toJson = new ToJson<>(1, "err");
        try {
            RepField repField = repFieldMapper.selectByPrimaryKey(fieldId);
            toJson.setObject(repField);
            toJson.setFlag(0);
            toJson.setMsg("true");
        } catch (Exception e) {
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    @Override
    public ToJson<RepField> findRepField(RepField repField) {
        ToJson<RepField> toJson = new ToJson<>(1, "err");
        try {
            List<RepField> repTables = repFieldMapper.selectCondition(repField);
            toJson.setObj(repTables);
            toJson.setFlag(0);
            toJson.setMsg("true");
        } catch (Exception e) {
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }


    @Override
    public ToJson<RepTable> getFieldByTableId(Integer tableId, Integer type) {
        ToJson<RepTable> toJson = new ToJson<>(1, "err");
        try {
            RepTable repTable = repTableMapper.selectByPrimaryKey(tableId);
            List<RepField> repTables;
            if (type != null && type == 1) {
                repTables = recursionField(tableId);
            } else {
                repTables = repFieldMapper.selectByTableId(tableId);
            }
            repTable.setRepFieldList(repTables);
            toJson.setObject(repTable);
            toJson.setFlag(0);
            toJson.setMsg("true");
        } catch (Exception e) {
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    //递归查询所有字段
    public List<RepField> recursionField(Integer tableId) {
        //查询没有分组的字段
        List<RepField> repFieldList = repFieldMapper.selectClassByTableId(tableId);
        //查询按照分组分组
        List<RepField> repFieldList1 = repFieldMapper.selectGroup(tableId);
        for (RepField repField : repFieldList1) {
            List<RepField> repFieldList2 = repFieldMapper.selectByGroup(tableId, repField.getFieldGroup());
            repField.setChildren(repFieldList2);
        }
        repFieldList.addAll(repFieldList1);
        Comparator<RepField> com1 = new Comparator<RepField>() {
            @Override
            public int compare(RepField r1, RepField r2) {
                return (r1.getFiledNo() - r2.getFiledNo());
            }
        };
        Collections.sort(repFieldList, com1);
        return repFieldList;
    }

}
